import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/login.vue'
import UserInfo from '@/views/UserInfo.vue'
import RegisterView from '@/views/Register.vue'
import NotFound from '@/views/404.vue'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        requiresAuth: false
      }
    },
    {
      path: '/role-square',
      name: 'roleSquare',
      component: HomeView, // 修改为使用HomeView布局
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/user-info',
      name: 'userInfo',
      component: UserInfo,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/chat/:id',
      name: 'chat',
      component: HomeView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/register',
      name: 'Register',
      component: RegisterView,
      meta: {
        requiresAuth: false
      }
    },
    {
       path: '/:catchAll(.*)',
       name: 'NotFound',
       component: NotFound,
       meta: {
          requiresAuth: false
       }
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = localStorage.getItem('token')

  // 判断该路由是否需要登录权限
  if (to.meta.requiresAuth) {
    // 需要登录权限
    if (token) {
      // 已登录，放行
      next()
    } else {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将要跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    // 不需要登录权限
    if (to.path === '/login' && token) {
      // 已登录状态下访问登录页，跳转到首页
      next({ path: '/' })
    } else {
      // 放行
      next()
    }
  }
})

export default router
